package oylj.recycle.all_in_one.pound;


import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.webkit.JavascriptInterface;

import java.io.InputStream;
import java.net.Socket;

import oylj.recycle.all_in_one.SystemConfig;


public class WeightLib {
    private static final String TAG = "WeightLib";
    private boolean isInitialized;
    private double weight;
    private  Socket socket;
    private Thread readThread;
    public WeightLib(){
    }
    public void start( SystemConfig.Pound poundConfig){
        new Thread(new Runnable(){
            @Override
            public void run(){
                try {
                    //1.创建客户端Socket，指定服务器地址和端口
                    socket = new Socket(poundConfig.getIp(), poundConfig.getPort());
                    //从socket获取输入输出流
                    InputStream is = socket.getInputStream();
                    readThread = new Thread(new Runnable(){
                        @Override
                        public void run(){
                            String content = "";
                            while (true) {
                                if (socket != null&&socket.isConnected()&&!socket.isInputShutdown()) {
                                    try {
                                        String number = "";
                                        byte[] data = new byte[poundConfig.getDataLength()];
                                        is.read(data);
                                        content = new String(data);
//                                            Log.d(TAG, "run: content "+content);
                                        number = content.substring(poundConfig.getDataStart(), poundConfig.getDataEnd());
//                                            Log.d(TAG, "run: number "+number);
                                        if(poundConfig.getReverse().equals("1")){
                                            number = new StringBuilder(number).reverse().toString();
                                        }
                                        if(poundConfig.getCheck().equals("1")){
                                            String validNumber = content.substring(poundConfig.getCheckDataStart(), poundConfig.getCheckDataEnd());
                                            String validString = content.substring(poundConfig.getCheckValueStart(), poundConfig.getCheckValueEnd());
                                            int xorNumber = xor(validNumber);
                                            if (!Integer.toHexString(xorNumber).equalsIgnoreCase(validString)){
                                                continue;
                                            }
                                        }
                                        isInitialized = true;
                                        weight = Double.parseDouble(number);
                                        Log.d(TAG, "run: weight "+weight);
                                    } catch (Exception e) {
                                        Log.e(TAG, "error: "+e.getMessage());
                                    }
                                }
                            }
                        }
                    });
                    readThread.start();
                } catch (Exception e ) {
                    Log.e(TAG, "run: "+e);
                }
            }
        }).start();
    }
    public boolean isInitialized() {
        return isInitialized;
    }
    @JavascriptInterface
    public double getWeight(){
        return weight;
    }
    private int xor(String string){
        // 初始化异或结果为第一个字符的ASCII码
        int xorResult = (int) string.charAt(0);

        // 依次对后续字符进行异或
        for (int i = 1; i < string.length(); i++) {
            xorResult ^= (int) string.charAt(i);
        }
        return xorResult;
    }

    /** 停止并销毁 WeightLib，安全关闭线程和 socket */
    public synchronized void destroy() {

        // 再关闭 socket
        if (socket != null) {
            try { socket.close(); } catch (Exception ignored) {}
            socket = null;
        }

        // 先中断读线程
        if (readThread != null && readThread.isAlive()) {
            readThread.interrupt();
            readThread = null;
        }

        isInitialized = false;
        weight = 0;

        Log.d(TAG, "WeightLib destroyed");
    }

}
